<script lang="ts" setup>
import { ref, reactive, onMounted, h } from 'vue';
import {
  Alert,
  Card,
  Table,
  Button,
  Tag,
  Space,
  Input,
  Select,
  DatePicker,
  message,
  Modal,
  Form,
  Upload,
  Spin,
  Switch,
} from 'ant-design-vue';
import type { TableColumnsType } from 'ant-design-vue';
import type { UploadFile } from 'ant-design-vue';
import { useRouter } from 'vue-router';
import {
  getTaskListApi,
  createSettlementApi,
  getSettlementLandingCompanyOptionsApi,
  getTaskQrCodeApi,
  updateTaskStatusApi,
  type TaskApi,
  type SettlementApi,
} from '#/api';

/**
 * 任务记录接口定义
 */
interface TaskRecord {
  id: string;
  name: string; // 任务名称
  service_type: string; // 任务类型
  status: 'inactive' | 'active'; // 任务状态
  start_time: string; // 开始时间
  end_time: string; // 结束时间
  min_fee: number; // 最低计费
  max_fee: number; // 最高计费
  billing_unit?: string; // 计费单位
  work_location: string; // 工作地点
  created_at: string; // 创建时间
}

/**
 * 分页参数接口
 */
interface PaginationParams {
  current: number;
  pageSize: number;
  total: number;
}

const router = useRouter();
const loading = ref(false);
const searchText = ref(''); // 任务名称搜索
const statusFilter = ref<'inactive' | 'active' | ''>(''); // 状态筛选
const taskData = ref<TaskRecord[]>([]);
const pagination = ref<PaginationParams>({
  current: 1,
  pageSize: 10,
  total: 0,
});

const statusUpdating = reactive<Record<string, boolean>>({});

const currentTask = ref<TaskRecord | null>(null);
const settlementModalVisible = ref(false);
const settlementSubmitting = ref(false);
const landingCompanyOptions = ref<Array<{ label: string; value: string; raw: SettlementApi.LandingCompanyOption }>>([]);
const landingCompanyLoading = ref(false);

const qrModalVisible = ref(false);
const qrLoading = ref(false);
const qrTaskName = ref('');
const qrImageSrc = ref('');
const qrDownloadFileName = ref('');

const settlementForm = reactive({
  landingCompany: undefined as string | number | undefined,
  settlementChannel: 'bank_card',
});

const settlementFileList = ref<UploadFile[]>([]);
const deliverableFileList = ref<UploadFile[]>([]);

/**
 * 表格列定义
 */
const columns: TableColumnsType<TaskRecord> = [
  {
    title: '任务ID',
    dataIndex: 'id',
    key: 'id',
    width: 80,
  },
  {
    title: '任务名称',
    dataIndex: 'name',
    key: 'name',
    width: 200,
  },
  {
    title: '任务类型',
    dataIndex: 'service_type',
    key: 'service_type',
    width: 120,
  },
  {
    title: '任务状态',
    dataIndex: 'status',
    key: 'status',
    width: 100,
    customRender: ({ record }) => {
      const statusMap = {
        inactive: { color: 'default', text: '未生效' },
        active: { color: 'success', text: '生效中' },
      };
      const status = statusMap[record.status];
      return h(Tag, { color: status.color }, () => status.text);
    },
  },
  {
    title: '任务周期',
    key: 'period',
    width: 200,
    customRender: ({ record }) => {
      return `${record.start_time} ~ ${record.end_time}`;
    },
  },
  {
    title: '任务计费',
    key: 'fee_range',
    width: 150,
    customRender: ({ record }) => {
      const unitLabel = record.billing_unit ? `/${record.billing_unit}` : '';
      return `¥${record.min_fee} ~ ¥${record.max_fee}${unitLabel}`;
    },
  },
  {
    title: '工作地点',
    dataIndex: 'work_location',
    key: 'work_location',
    width: 150,
  },
  {
    title: '创建时间',
    dataIndex: 'created_at',
    key: 'created_at',
    width: 150,
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
    fixed: 'right',
    customRender: ({ record }) => {
      return h(Space, {}, () => [
        h(Switch, {
          checked: record.status === 'active',
          checkedChildren: '启用',
          unCheckedChildren: '禁用',
          loading: Boolean(statusUpdating[record.id]),
          onChange: (checked: boolean) => handleToggleTaskStatus(record, checked),
        }),
        h(Button, {
          type: 'link',
          size: 'small',
          onClick: () => handleViewDetail(record.id)
        }, () => '详情'),
        h(
          Button,
          {
            type: 'link',
            size: 'small',
            onClick: () => handleEditTask(record.id),
          },
          () => '编辑',
        ),
        h(
          Button,
          {
            type: 'link',
            size: 'small',
            onClick: () => handleShowQrModal(record),
          },
          () => '二维码',
        ),
        h(Button, {
          type: 'link',
          size: 'small',
          onClick: () => openSettlementModal(record),
        }, () => '结算'),
      ]);
    },
  },
];

/**
 * 获取任务数据
 */
const fetchTaskData = async () => {
  loading.value = true;
  try {
    const response = await getTaskListApi({
      page: pagination.value.current,
      per_page: pagination.value.pageSize,
      search: searchText.value || undefined,
      status: statusFilter.value || undefined,
    });
    
    // 数据转换处理
    taskData.value = response.data.map((item: any) => ({
      ...item,
      id: String(item.id), // 转换为字符串
      start_time: item.start_time ? new Date(item.start_time).toISOString().split('T')[0] : '',
      end_time: item.end_time ? new Date(item.end_time).toISOString().split('T')[0] : '',
      created_at: item.created_at ? new Date(item.created_at).toISOString().split('T')[0] : '',
      min_fee: parseFloat(item.min_fee) || 0,
      max_fee: parseFloat(item.max_fee) || 0,
      billing_unit: item.billing_unit || '',
    }));
    
    pagination.value.total = response.total;
    pagination.value.current = response.current_page;
  } catch (error) {
    console.error('获取任务数据失败:', error);
    message.error('获取任务数据失败，请稍后重试');
  } finally {
    loading.value = false;
  }
};

/**
 * 重置查询条件
 */
const resetFilters = () => {
  searchText.value = '';
  statusFilter.value = '';
  pagination.value.current = 1;
  fetchTaskData();
};

/**
 * 发布任务处理函数（占位）
 */
const handlePublishTask = () => {
  router.push({ name: 'TaskPublish' });
};

/**
 * 分页变化处理
 */
const handleTableChange = (pag: any) => {
  pagination.value.current = pag.current;
  pagination.value.pageSize = pag.pageSize;
  fetchTaskData();
};

/**
 * 查看任务详情
 */
const handleViewDetail = (taskId: string) => {
  router.push(`/settlement/task-detail/${taskId}`);
};

const handleEditTask = (taskId: string) => {
  router.push({ name: 'TaskPublish', query: { taskId } });
};

const handleToggleTaskStatus = async (record: TaskRecord, checked: boolean) => {
  const previousStatus = record.status;
  const nextStatus: TaskRecord['status'] = checked ? 'active' : 'inactive';

  if (previousStatus === nextStatus) {
    return;
  }

  statusUpdating[record.id] = true;
  record.status = nextStatus;

  try {
    await updateTaskStatusApi(record.id, nextStatus);
    message.success(nextStatus === 'active' ? '任务已生效' : '任务已设为未生效');
  } catch (error) {
    console.error('更新任务状态失败:', error);
    record.status = previousStatus;
    message.error('更新任务状态失败，请稍后重试');
  } finally {
    statusUpdating[record.id] = false;
  }
};

const handleShowQrModal = async (record: TaskRecord) => {
  qrTaskName.value = record.name;
  qrDownloadFileName.value = `task-${record.id}-qrcode.png`;
  qrModalVisible.value = true;
  qrLoading.value = true;
  try {
    const qrData = await getTaskQrCodeApi(record.id);
    qrImageSrc.value = `data:image/png;base64,${qrData.qr_image_base64}`;
    qrTaskName.value = qrData.task_name || record.name;
    qrDownloadFileName.value = `task-${qrData.task_id}-qrcode.png`;
  } catch (error) {
    console.error('获取任务二维码失败', error);
    message.error('获取二维码失败，请稍后重试');
    qrModalVisible.value = false;
  } finally {
    qrLoading.value = false;
  }
};

const handleDownloadQr = () => {
  if (!qrImageSrc.value) return;
  const link = document.createElement('a');
  link.href = qrImageSrc.value;
  link.download = qrDownloadFileName.value || 'task-qrcode.png';
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
};

const closeQrModal = () => {
  qrModalVisible.value = false;
  qrLoading.value = false;
  qrImageSrc.value = '';
  qrTaskName.value = '';
};

const resetSettlementForm = () => {
  settlementForm.landingCompany = landingCompanyOptions.value[0]?.value;
  settlementForm.settlementChannel = 'bank_card';
  settlementFileList.value = [];
  deliverableFileList.value = [];
  settlementAttachment.value = null;
  deliverableAttachment.value = null;
};

const fetchLandingCompanies = async () => {
  if (landingCompanyOptions.value.length || landingCompanyLoading.value) return;
  landingCompanyLoading.value = true;
  try {
    const options = await getSettlementLandingCompanyOptionsApi();
    landingCompanyOptions.value = options.map((item) => ({
      label: item.label || item.name || String(item.value ?? ''),
      value: String(item.value ?? item.code ?? item.name ?? ''),
      raw: item,
    }));
    if (landingCompanyOptions.value.length > 0) {
      settlementForm.landingCompany = landingCompanyOptions.value[0].value;
    }
  } catch (error) {
    console.error('获取落地公司选项失败:', error);
    message.error('获取落地公司选项失败，请稍后重试');
  } finally {
    landingCompanyLoading.value = false;
  }
};

const settlementAttachment = ref<File | null>(null);
const deliverableAttachment = ref<File | null>(null);

const openSettlementModal = (record: TaskRecord) => {
  currentTask.value = record;
  resetSettlementForm();
  settlementModalVisible.value = true;
  fetchLandingCompanies();
};

const handleSettlementFileChange = (info: any) => {
  const fileList = info.fileList.slice(-1);
  settlementFileList.value = fileList.map((file: UploadFile) => ({
    ...file,
    status: 'done',
  }));
  const latest = fileList[0];
  const originFile =
    (latest?.originFileObj as File | undefined) ||
    (info.file?.originFileObj as File | undefined);
  settlementAttachment.value = originFile ?? null;
};

const handleDeliverableFileChange = (info: any) => {
  const fileList = info.fileList.slice(-1);
  deliverableFileList.value = fileList.map((file: UploadFile) => ({
    ...file,
    status: 'done',
  }));
  const latest = fileList[0];
  const originFile =
    (latest?.originFileObj as File | undefined) ||
    (info.file?.originFileObj as File | undefined);
  deliverableAttachment.value = originFile ?? null;
};

const handleSettlementFileRemove = () => {
  settlementFileList.value = [];
  settlementAttachment.value = null;
  return true;
};

const handleDeliverableFileRemove = () => {
  deliverableFileList.value = [];
  deliverableAttachment.value = null;
  return true;
};

const settlementTemplateUrl = '/settlement-template.xlsx';

const handleSettlementTemplateDownload = () => {
  try {
    const link = document.createElement('a');
    link.href = settlementTemplateUrl;
    link.download = 'settlement-template.xlsx';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  } catch (error) {
    console.warn('模板下载失败', error);
    message.error('下载失败，请稍后再试');
  }
};

const handleSettlementCancel = () => {
  settlementModalVisible.value = false;
  resetSettlementForm();
};

const handleSettlementSubmit = async () => {
  if (!currentTask.value) {
    message.error('未找到任务信息');
    return;
  }

  if (!settlementForm.landingCompany) {
    message.error('请选择落地公司');
    return;
  }

  if (!settlementAttachment.value) {
    message.error('请上传结算单');
    return;
  }

  try {
    settlementSubmitting.value = true;
    const formData = new FormData();
    formData.append('task_id', currentTask.value.id);
    formData.append('landing_company', String(settlementForm.landingCompany));
    formData.append('settlement_channel', settlementForm.settlementChannel);
    const settlementFile = settlementAttachment.value;
    if (settlementFile) {
      formData.append(
        'settlement_file',
        settlementFile,
        settlementFile.name || `${currentTask.value.id}_settlement.xls`,
      );
    }
    if (deliverableAttachment.value) {
      const deliverableFile = deliverableAttachment.value;
      formData.append(
        'deliverable_file',
        deliverableFile,
        deliverableFile.name || `${currentTask.value.id}_deliverable.xls`,
      );
    }

    await createSettlementApi(formData);
    message.success('结算单提交成功');
    handleSettlementCancel();
    fetchTaskData();
  } catch (error: any) {
    console.error('结算单提交失败:', error);
    message.error(error?.message || '结算单提交失败，请稍后重试');
  } finally {
    settlementSubmitting.value = false;
  }
};

onMounted(() => {
  fetchTaskData();
});
</script>

<template>
  <div class="p-5">
    <Card title="任务中心" class="mb-4">
      <!-- 搜索和筛选区域 -->
      <div class="mb-4 flex flex-wrap gap-4">
        <Input.Search
          v-model:value="searchText"
          placeholder="搜索任务名称"
          style="width: 200px"
          @search="fetchTaskData"
        />
        <Select
          v-model:value="statusFilter"
          placeholder="选择状态"
          style="width: 120px"
          allowClear
        >
          <Select.Option value="inactive">未生效</Select.Option>
          <Select.Option value="active">生效中</Select.Option>
        </Select>
        <Button type="primary" @click="fetchTaskData">查询</Button>
        <Button @click="resetFilters">重置</Button>
        <Button type="primary" @click="handlePublishTask">+发布任务</Button>
      </div>
      
      <!-- 任务列表 -->
      <Table
        :columns="columns"
        :data-source="taskData"
        :loading="loading"
        row-key="id"
        :pagination="{
          current: pagination.current,
          pageSize: pagination.pageSize,
          total: pagination.total,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
        }"
        @change="handleTableChange"
      />
    </Card>

    <Modal
      v-model:open="settlementModalVisible"
      title="上传结算单"
      :confirm-loading="settlementSubmitting"
      :mask-closable="false"
      destroy-on-close
      @cancel="handleSettlementCancel"
    >
      <Form layout="vertical">
        <Form.Item label="任务">
          <Input :value="currentTask?.name || '-'" disabled />
        </Form.Item>
        <Form.Item label="落地公司" required>
          <Select
            v-model:value="settlementForm.landingCompany"
            :options="landingCompanyOptions"
            :loading="landingCompanyLoading"
            disabled
          />
        </Form.Item>
        <Form.Item label="结算渠道">
          <Input value="银行卡" disabled />
        </Form.Item>
        <Form.Item label="上传结算单" required>
          <Upload
            :before-upload="() => false"
            :file-list="settlementFileList"
            @change="handleSettlementFileChange"
            @remove="handleSettlementFileRemove"
            :max-count="1"
            accept=".xlsx,.xls"
          >
            <Button type="dashed">选择结算单</Button>
          </Upload>
          <div class="mt-2 text-xs text-gray-500">支持 .xlsx / .xls 格式，文件大小建议不超过 10MB</div>
        </Form.Item>
        <Form.Item label="交付物">
          <Upload
            :before-upload="() => false"
            :file-list="deliverableFileList"
            @change="handleDeliverableFileChange"
            @remove="handleDeliverableFileRemove"
            :max-count="1"
          >
            <Button type="dashed">上传交付物（选填）</Button>
          </Upload>
        </Form.Item>
      </Form>
      <template #footer>
        <div class="flex items-center justify-between">
          <Button type="link" @click="handleSettlementTemplateDownload">模板下载</Button>
          <div class="space-x-2">
            <Button @click="handleSettlementCancel">取消</Button>
            <Button type="primary" :loading="settlementSubmitting" @click="handleSettlementSubmit">
              确定
            </Button>
          </div>
        </div>
      </template>
    </Modal>

    <Modal
      v-model:open="qrModalVisible"
      title="任务二维码"
      :mask-closable="false"
      destroy-on-close
      @cancel="closeQrModal"
    >
      <div class="qr-modal-body">
        <Alert message="将二维码分享给自由职业者完成报名" type="info" show-icon />
        <div class="qr-modal-content">
          <Spin :spinning="qrLoading">
            <div class="qr-image-wrapper" v-if="qrImageSrc">
              <img :src="qrImageSrc" alt="任务二维码" />
            </div>
          </Spin>
          <div class="qr-task-name">{{ qrTaskName }}</div>
        </div>
      </div>
      <template #footer>
        <Space>
          <Button type="primary" ghost :disabled="!qrImageSrc" @click="handleDownloadQr">
            下载二维码
          </Button>
          <Button type="primary" @click="closeQrModal">确定</Button>
        </Space>
      </template>
    </Modal>
  </div>
</template>

<style scoped>
.qr-modal-body {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.qr-modal-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
}

.qr-image-wrapper {
  width: 240px;
  height: 240px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #fff;
  padding: 8px;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.qr-image-wrapper img {
  max-width: 100%;
  height: auto;
}

.qr-task-name {
  font-size: 16px;
  font-weight: 500;
  color: #1f2937;
  text-align: center;
}
</style>
